#include "file.h"
#include "wifiset.h"
#include "mqtt.h"

void(* resetFunct) (void) = 0;

char msg[71];

void setup() {
  // put your setup code here, to run once:
  file_system_begin();
  //config_file_remove();
  if (config_file_exist()) 
  {
	  read_file();
	  Serial.begin(atoi(config_info.bps));
	  wifi_connect();
  }
  else 
  {
	  Serial.begin(9600);
	  wifi_init();
	  print_file();
  }
  
  Serial.setTimeout(200);
  pinMode(0,OUTPUT);

  mqtt_init(); 

  Serial.println(WiFi.localIP());
  Serial.println("OK!");
  digitalWrite(0,0);
}

void loop() {
  // put your main code here, to run repeatedly:
  mqtt_loop();

  uint8_t len = Serial.readBytesUntil('\n', msg, 60);
  if (len > 51)
  {
    bool flag_reset = 1;
    for (char b = 0; b < len; b++)
    {
      if (msg[b] != 'R') flag_reset = 0;
    }
    if (flag_reset) {
      config_file_remove();
      Serial.println("RESET !!!");
      resetFunct();
    }
  } 
  else if (len >= 1 && msg[len - 1])
  {
    digitalWrite(0,1);
    Pub_Info(msg);
    memset(msg, 0, len);
  }
}
